package cn.dengta.webapp.ai.model;

import javax.annotation.Nullable;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import me.codeplayer.util.X;

/**
 * AI 聊天消息的通用类，用于构建prompt，只支持文本消息，音频内容需自行转化为文本
 */
@Getter
@Setter
public class AIGCMessage {

	public static final String USER = "user";
	public static final String AI = "ai";

	String type;
	@Setter
	@Accessors(chain = true)
	String sendName;
	String content;
	/** 时间戳，秒 */
	private Long created;

	/** 是否记忆 */
	@Setter
	@JSONField(serialize = false)
	boolean remember = true;

	private AIGCMessage() {
	}

	@JSONField(serialize = false)
	public boolean isUser() {
		return USER.equals(type);
	}

	@JSONField(serialize = false)
	public boolean isAi() {
		return AI.equals(type);
	}

	public static AIGCMessage fromAi(@NotNull String content, @Nullable Long createdSec, boolean remember) {
		AIGCMessage aigcMessage = new AIGCMessage();
		aigcMessage.type = AI;
		aigcMessage.content = content;
		aigcMessage.remember = remember;
		aigcMessage.created = X.expectNotNull(createdSec, System.currentTimeMillis() / 1000L);
		return aigcMessage;
	}

	public static AIGCMessage fromAi(@NotNull String content, @Nullable Long createdSec) {
		return fromAi(content, createdSec, true);
	}

	public static AIGCMessage fromUser(@NotNull String content) {
		return fromUser(content, null, true);
	}

	public static AIGCMessage fromUser(@NotNull String content, @Nullable Long createdSec) {
		return fromUser(content, createdSec, true);
	}

	public static AIGCMessage fromUser(@NotNull String content, @Nullable Long createdSec, boolean remember) {
		AIGCMessage aigcMessage = new AIGCMessage();
		aigcMessage.type = USER;
		aigcMessage.content = content;
		aigcMessage.created = X.expectNotNull(createdSec, System.currentTimeMillis() / 1000L);
		aigcMessage.remember = remember;
		return aigcMessage;
	}

	public boolean after(@NotNull AIGCMessage other) {
		return created > other.created;
	}

	public boolean before(@NotNull AIGCMessage other) {
		return created < other.created;
	}

	public void validate() {
		if (type != null && sendName != null && content != null && created != null) {
			return;
		}
		throw new IllegalArgumentException("【AIGC】Invalid AIGCMessage: " + content);

	}

	public void validateSample() {
		if (type != null && content != null) {
			return;
		}
		throw new IllegalArgumentException("【AIGC】Invalid Sample: " + content);

	}

	public static AIGCMessage from(@NotEmpty String json) {
		AIGCMessage aigcMessages = JSON.parseObject(json, AIGCMessage.class);
		aigcMessages.validate();
		return aigcMessages;
	}

}
